package top.ghovos.edgar.springbootproject03.controllers;

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import top.ghovos.edgar.springbootproject03.models.RegionStats;
import top.ghovos.edgar.springbootproject03.services.CoronaVirusDataServices;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;


@Controller
public class HomeController {
    private final CoronaVirusDataServices coronaVirusDataServices;

    public HomeController(CoronaVirusDataServices coronaVirusDataServices) {
        this.coronaVirusDataServices = coronaVirusDataServices;
    }

    @GetMapping("/")
    public String home(Model model, String country) {
        List<RegionStats> allStats;
        if (country == null) {
            allStats = coronaVirusDataServices.getAllRegionStats();
        } else {
            allStats = coronaVirusDataServices.getAllRegionStats()
                    .parallelStream()
                    .filter(locationStats -> locationStats.getCountry().equals(country))
                    .collect(Collectors.toUnmodifiableList());
        }

        model.addAttribute("country", country);


        int totalReportedCases = allStats.parallelStream().mapToInt(RegionStats::getLatestTotalCases).sum();
        int totalNewCases = allStats.parallelStream().mapToInt(RegionStats::getDiffFromPrevDay).sum();


        int totalLastTenDaysCases[]=new int[10];
        for (int n = 0; n < 10; n++) {
            totalLastTenDaysCases[n]=0;
            for(int m=0;m<allStats.size();m++){
                totalLastTenDaysCases[n]=totalLastTenDaysCases[n]+allStats.get(m).getLastTenDaysCases()[n];
            }
        }

        model.addAttribute("regionStats", allStats);
        model.addAttribute("totalReportedCases", totalReportedCases);
        model.addAttribute("totalNewCases", totalNewCases);
        model.addAttribute("localDate", LocalDate.now());
        model.addAttribute("lastTenDaysCases",totalLastTenDaysCases);
        return "index";
    }
}
